package com.climber.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
public class PageController {

    @GetMapping("/")
    public String index() {
        System.out.println("hello");
        int a=1/0;
        return "index";
    }

    @GetMapping("noReturn/download")
    public void noReturn(@RequestParam String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("下载文件的名称：" + fileName);
        // 1. 根据下载相对目录获取下载目录在服务器部署之后绝对目录
//        String realPath = request.getSession().getServletContext().getRealPath("");
        String realPath ="F:/个人总结" ;
        // 2. 通过文件输入流读取文件
        System.out.println(realPath);
        FileInputStream is = new FileInputStream(new File(realPath, fileName));

        // 3. 获取响应输出流
        response.setContentType("text/plain;charset=UTF-8");
        // 4. 附件下载 attachment 附件 inline 在线打开(默认值)
        response.setHeader("content-disposition", "attachment;fileName=" + fileName);
        // 5. 处理下载流复制
        ServletOutputStream os = response.getOutputStream();
        int len;
        byte[] b = new byte[1024];
        while(true){
            len = is.read(b);
            if(len == -1) break;
            os.write(b, 0, len);
        }
        // 释放资源
        os.close();
        is.close();
    }





}
